<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { appletmsupdate, appletmsquery, appletmsdel, appletmsadd } from "@/api/combo-xcx"
import { type IGetComboData } from "@/api/combo/types/combo"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { Plus } from "@element-plus/icons-vue"
import { uploadComboImageList } from "@/api/combo"
import { useUserStore } from "@/store/modules/user"
const userStore = useUserStore()

defineOptions({
  name: "ComboXcxduoduan"
})
const fileList = ref<any>([]) /**图片列表 */
// const userStore = useUserStore()
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive<any>({ data: { colors: "#00ced1" } })
const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入套餐名称" }],
  package_super: [{ required: true, trigger: "blur", message: "请选择套餐" }],
  operator: [{ required: true, trigger: "blur", message: "请选择运营商" }],
  type: [{ required: true, trigger: "blur", message: "请选择小程序" }],
  up: [{ required: true, trigger: "blur", message: "请选择是否上架" }]
})
const handleAdd = () => {
  dialogVisible.value = true
  // formData.data.team = userStore.userInfo.team
}
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      uploadFuc()
    } else {
      return false
    }
  })
}
const predefineColors = ref([
  "#ff4500",
  "#ff8c00",
  "#ffd700",
  "#90ee90",
  "#00ced1",
  "#1e90ff",
  "#c71585",
  "rgba(255, 69, 0, 0.68)",
  "rgb(255, 120, 0)",
  "hsv(51, 100, 98)",
  "hsva(120, 40, 94, 0.5)",
  "hsl(181, 100%, 37%)",
  "hsla(209, 100%, 56%, 0.73)",
  "#c7158577"
])
//#endregion

//小程序平台
import { getAppletDataApi } from "@/api/applet"
const clientList = ref<any>([])

const getApplet = () => {
  getAppletDataApi({
    page: 1,
    size: 100
  })
    .then((res: any) => {
      clientList.value = res.data.list
    })
    .catch(() => {
      clientList.value = []
    })
}
getApplet()

//#region 删
const handleDelete = (row: IGetComboData) => {
  ElMessageBox.confirm(`正在删除套餐：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    appletmsdel(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)

const handleUpdate = (row: any) => {
  // console.log(row)
  currentUpdateId.value = row.id
  formData.data = JSON.parse(JSON.stringify(row))
  formData.data.up = row.up
  if (row.back) {
    fileList.value = row.back?.split(",").map((item: any) => {
      return {
        url: `http://fansitexitong.cn/image/${item}`
        // url: `http://192.168.31.143:8080/image/${item}`
      }
    })
  }

  if (row.img) {
    fileList1.value = row.img?.split(",").map((item: any) => {
      return {
        url: `http://fansitexitong.cn/image/${item}`
        // url: `http://192.168.31.143:8080/image/${item}`
      }
    })
  }
  formData.data.id = currentUpdateId.value
  dialogVisible.value = true
  console.log(row.img)
}
//#endregion

//#region 查
const tableData = ref<IGetComboData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  type: "",
  sku: "",
  superSku: "",
  state: "true"
  // team: userStore.teamName ? userStore.teamName : ""
})
const getTableData = () => {
  loading.value = true
  appletmsquery({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name,
    team: userStore.userInfo.user.team

    // type: searchData.type
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}
//#endregion
/**套餐详情图上传 */
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList.value = []
  } else {
    fileList.value = resfileList
  }
}

// 预览图片
const dialogImageUrl = ref("") /**预览url  */
const dialogVisible1 = ref(false) /**预览弹窗 */
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible1.value = true
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList.value = list
}
//确定上传
const uploadFuc = async () => {
  if (fileList.value.length === 0) {
    ElMessage.error("请上传套餐详情图")
    return
  }
  const fileData = new FormData()
  fileList.value.forEach((file: any) => {
    fileData.append("file", file.raw)
  })
  if (fileList.value[0].status === "ready") {
    await uploadComboImageList(fileData).then((res: any) => {
      if (res.code == 200) {
        formData.data.back = res.data.split("/image/")[1]
        fileList.value = []
      }
    })
  }

  if (currentUpdateId.value === undefined) {
    await appletmsadd(formData.data).then(() => {
      ElMessage.success("新增成功")
      dialogVisible.value = false
      getTableData()
    })
  } else {
    await appletmsupdate(formData.data).then(() => {
      ElMessage.success("修改成功")
      dialogVisible.value = false
      getTableData()
    })
  }
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/**监听套餐缓存(pinia) */
import { useComboStore } from "@/store/modules/combo"
const comboStore = useComboStore()
comboStore.getComoboFn()
const comboList = ref<any>([])
const comboList1 = ref<any>([])
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
    comboList1.value = newValue.flat().filter((item) => item.state === "true")
  },
  {
    immediate: true
  }
)
//上传套餐展示图
import { getToken } from "@/utils/cache/cookies"
import type { UploadProps } from "element-plus"

const fileList1 = ref<any>([]) /**图片列表 */
const dialogVisible4 = ref<boolean>(false)
const dialogImageUrl4 = ref<any>("")

const handleChageImg1 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList1.value = resfileList.filter((item: any) => item.uid !== file.uid) /**不符合规定的图片不在照片墙展示 */
  } else {
    // fileList1.value = resfileList
    // console.log(fileList1.value, 192)
    formData.data.img = resfileList
      .map((item: any) => {
        return item.response?.data.split("/image/")[1]
          ? item.response?.data.split("/image/")[1]
          : item.url.split("/image/")[1]
      })
      .join(",")
  }
}

const handleRemove1: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFiles, 180)
  // fileList1.value = uploadFiles
  formData.data.img = uploadFiles
    .map((item: any) => {
      return item.response?.data.split("/image/")[1]
        ? item.response?.data.split("/image/")[1]
        : item.url.split("/image/")[1]
    })
    .join(",")
}

const handlePictureCardPreview1: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl4.value = uploadFile.url!
  dialogVisible4.value = true
}

const headersOpts = {
  token: getToken()
}

/**department END */
// console.log(departTeam.value)

// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  formData.data = { colors: "#00ced1" }
  fileList.value = []
  fileList1.value = []
  formData.data.img = ""
  formData.data.back = ""
  clearValidate()
}

const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.package_super) {
      celValue = item.name
    }
  })
  return celValue
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="套餐名">
          <el-input v-model.trim="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="type" label="小程序" v-if="userStore.userInfo.user.role === '超级管理员'">
          <!-- <el-select v-model="searchData.type" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="抖音小程序" :value="1" />
            <el-option :key="0" label="支付宝小程序" :value="0" />
          </el-select> -->
          <el-select v-model="searchData.type" filterable clearable style="width: 240px">
            <el-option v-for="item in clientList" :key="item.code" :label="item.name" :value="item.code"
          /></el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加套餐</el-button>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="img" label="套餐封面图" align="center">
            <template #default="scope">
              <img
                :src="`http://fansitexitong.cn/image/${scope.row.img?.split(',')[0]}`"
                alt=""
                width="80"
                height="80"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="套餐名" align="center" />
          <el-table-column
            prop="package_super"
            label="系统对应套餐"
            align="center"
            :formatter="formatterCombo"
            width="220"
          />
          <el-table-column prop="operator" label="运营商" align="center">
            <template #default="scope">
              <span v-if="scope.row.operator == 1">移动</span>
              <span v-else-if="scope.row.operator == 2">联通</span>
              <span v-else-if="scope.row.operator == 3">电信</span>
              <span v-else-if="scope.row.operator == 4">广电</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="小程序" align="center">
            <template #default="scope">
              <!-- <span v-if="scope.row.type == 1">抖音小程序</span>
              <span v-else-if="scope.row.type == 0">支付宝小程序</span> -->
              <el-select v-model="scope.row.type" filterable clearable style="width: 200px" disabled>
                <el-option v-for="item in clientList" :key="item.code" :label="item.name" :value="Number(item.code)"
              /></el-select>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="date" label="发布时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.date) }}
            </template>
          </el-table-column> -->
          <el-table-column fixed="right" label="操作" width="280" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增套餐' : '修改套餐'"
      @close="resetForm"
      width="80%"
    >
      <el-form
        class="forminput"
        ref="formRef"
        :model="formData.data"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item prop="name" label="套餐名">
          <el-input v-model="formData.data.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="package_super" label="系统对应套餐">
          <el-select
            v-model="formData.data.package_super"
            clearable
            filterable
            placeholder="请选套餐"
            style="width: 240px"
          >
            <el-option v-for="item in comboList1" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="operator" label="运营商">
          <el-select v-model="formData.data.operator" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="移动" :value="1" />
            <el-option :key="2" label="联通" :value="2" />
            <el-option :key="3" label="电信" :value="3" />
            <el-option :key="4" label="广电" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item prop="up" label="是否上架">
          <el-select v-model="formData.data.up" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="是" :value="true" />
            <el-option :key="2" label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item prop="shows" label="人气区展示">
          <el-select v-model="formData.data.shows" clearable placeholder="请选择" style="width: 240px">
            <el-option :key="1" label="是" value="是" />
            <el-option :key="2" label="否" value="否" />
          </el-select>
        </el-form-item>
        <el-form-item prop="colors" label="标题颜色">
          <el-color-picker v-model="formData.data.colors" show-alpha :predefine="predefineColors" />
        </el-form-item>
        <el-form-item prop="sorts" label="排序">
          <el-input v-model="formData.data.sorts" placeholder="填写数字,1该产品将排在第一位" />
        </el-form-item>
        <el-form-item prop="equity_one" label="标签1">
          <el-input v-model="formData.data.equity_one" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="equity_two" label="标签2">
          <el-input v-model="formData.data.equity_two" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="equity_three" label="标签3">
          <el-input v-model="formData.data.equity_three" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="hot" label="产品热度值">
          <el-input v-model="formData.data.hot" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item prop="team" label="团队" style="display: none">
          <el-input v-model="formData.data.team" placeholder="请输入" />
        </el-form-item> -->

        <!-- <el-form-item prop="type" label="对应小程序" style="display: none">
          <el-select v-model="formData.data.type" filterable clearable style="width: 240px">
            <el-option v-for="item in clientList" :key="item.code" :label="item.name" :value="Number(item.code)"
          /></el-select>
        </el-form-item> -->
        <el-form-item prop="img">
          <template #label>
            <span>套餐封面图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content>
                套餐封面图，颜色风格建议与标题颜色保持相近色值 建议尺寸宽高比 1.6:1 ,例如 宽320px 高
                200px,用于展示产品缩略图
              </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            v-model:file-list="fileList1"
            action="api/order/package/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview1"
            :on-remove="handleRemove1"
            :on-change="handleChageImg1"
            :headers="headersOpts"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible4">
            <img w-full :src="dialogImageUrl4" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item prop="back">
          <template #label>
            <span>套餐详情图</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content> 套餐详情图，建议尺寸 宽750px 高度随内容变化 用于小程序产品详情页的详情图 </template>
              <el-icon style="cursor: pointer"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            :on-change="handleChageImg"
            :disabled="fileList.length != 0"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.ageInput :deep(.el-input) {
  width: 20% !important;
}
.forminput {
  :deep(.el-form-item__label) {
    width: 130px !important;
  }
}

:deep(.el-popper) {
  max-width: 50% !important;
}
:deep(.el-cascader) {
  width: 567px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
